package com.jinjiafeng.framelibrary.banner;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jinjiafeng
 * Time :18-5-26
 */

class BannerViewPager extends ViewPager {
    private static final int MESSAGE_START_ROLL = 0;
    private BaseBannerAdapter mAdapter;
    /**
     * 自动轮播间隔
     */
    private int mScrollInterval;
    private int mCurrentIndex = 0;
    private Handler mHandler = new MyHandler(this);
    /**
     * 缓存viewpager 视图
     */
    private List<View> mConvertViews;
    private Activity mActivity;
    /**
     * 用来管理activity生命周期,onPause暂停轮播
     */
    private SimpleActivityLifecycleCallbacks mLifecycleCallbacks = new
            SimpleActivityLifecycleCallbacks() {
                @Override
                public void onActivityResumed(Activity activity) {
                    if (activity == mActivity) {
                        startAutoPlay();
                    }
                }

                @Override
                public void onActivityPaused(Activity activity) {
                    if (activity == mActivity) {
                        stopAutoPlay();
                    }
                }
            };

    BannerViewPager(Context context) {
        this(context, null);
    }


    BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        mActivity = (Activity) context;
    }

    void setScrollInterval(int scrollInterval) {
        mScrollInterval = scrollInterval;
    }

    void setAdapter(BaseBannerAdapter adapter) {
        mAdapter = adapter;
        mConvertViews = new ArrayList<>();
        //设置完adapter,开始轮播
        startAutoPlay();
        final MyPagerAdapter myPagerAdapter = new MyPagerAdapter();
        //注册生命周期监听
        mActivity.getApplication().registerActivityLifecycleCallbacks(mLifecycleCallbacks);
        //调用父类的setAdapter()
        super.setAdapter(myPagerAdapter);
    }

    private void startAutoPlay() {
        //当条目大小为1时,才开始轮播
        if (mAdapter.getCount() > 1) {
            //清除之前的任务
            stopAutoPlay();
            mHandler.sendEmptyMessageDelayed(MESSAGE_START_ROLL, mScrollInterval);
        }
    }

    private void stopAutoPlay() {
        mHandler.removeMessages(MESSAGE_START_ROLL);
    }

    /**
     * 处理事件分发,按下暂停轮播, 放开开始轮播
     *
     * @param ev MotionEvent
     * @return 消费
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
                || action == MotionEvent.ACTION_OUTSIDE) {
            startAutoPlay();
        } else if (action == MotionEvent.ACTION_DOWN) {
            stopAutoPlay();
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //内存优化,移除任务
        if (mHandler != null) {
            mHandler.removeMessages(MESSAGE_START_ROLL);
            //取消监听,防止泄露
            mActivity.getApplication().unregisterActivityLifecycleCallbacks(mLifecycleCallbacks);
            mHandler = null;
        }
    }

    private View getConvertView() {
        for (View view : mConvertViews) {
            //当已经被viewpagerAdapter移除后,直接返回缓存中的视图
            if (view.getParent() == null) {
                return view;
            }
        }
        return null;
    }

    private static class MyHandler extends Handler {
        /**
         * WeakReference 持有外部引用,来防止内存泄露
         */
        private final WeakReference<BannerViewPager> mViewPager;

        MyHandler(BannerViewPager viewPager) {
            super();
            mViewPager = new WeakReference<>(viewPager);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final BannerViewPager viewPager = mViewPager.get();
            viewPager.setCurrentItem(++viewPager.mCurrentIndex);
            viewPager.startAutoPlay();
        }
    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            final View view = mAdapter.bannerItem(position % mAdapter.getCount(),
                    getConvertView());
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object
                object) {
            container.removeView((View) object);
            mConvertViews.add((View) object);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }
    }
}
